package longrise.phone.com.bjjt_henan.Utils;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;

/**
 * 回收View控件占用的Bitmap对象
 */
public class RecycleBitmap {

    /**
     * 回收AbsListView类，如GridView,ListView等
     *
     * @param aListView
     */
    public static void recycleAbsListView(AbsListView aListView) {
        if (null == aListView) {
            return;
        }
        synchronized (aListView) {
            int count = aListView.getLastVisiblePosition();
            for (int i = aListView.getFirstVisiblePosition(); i < count; i++) {
                ViewGroup viewGroup = (ViewGroup) aListView.getAdapter().getView(i, null, aListView);
                recycleViewGroup(viewGroup);
            }
        }
    }

    /**
     * 回收ViewGroup类，如Linearlayout,RelativeLayout等
     *
     * @param viewGroup
     */
    public static void recycleViewGroup(ViewGroup viewGroup) {
        if (null == viewGroup) {
            return;
        }
        synchronized (viewGroup) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View subView = viewGroup.getChildAt(i);
                if (null != subView && subView instanceof ImageView) {
                    recycleImageView(subView);
                } else if (null != subView && subView instanceof ViewGroup) {
                    recycleViewGroup(viewGroup);
                }
            }
        }
    }

    /**
     * 回收ImageView占用的图像内存
     *
     * @param view
     */
    public static void recycleImageView(View view) {
        if (null == view) {
            return;
        }
        if (view instanceof ImageView) {
            Drawable drawable = ((ImageView) view).getDrawable();
            if (null != drawable && drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                if (null != bitmap && !bitmap.isRecycled()) {
                    ((ImageView) view).setImageBitmap(null);
//                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
//        System.gc();
    }
}
